package cn.com.kh.hst;

import cn.com.elite.Util;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.kh.hst
 * @className: apiGoogleTranslate
 * @author: LiJT
 * @description: TODO
 * @date: 2023-09-27 11:50
 * @version: 1.0
 */

public class GoogleTranslateAPI {
    private static final Log log = LogFactory.getLog(GoogleTranslateAPI.class);

    private static final String transURL = "https://translation.googleapis.com/language/translate/v2";
    private static final String apiKey = "AIzaSyAACAMsBWCxiElkIKFvf5T28IP9B7dsWi8";

    public static void main(String[] args) throws Exception {
        String text = "Hello,   world!";
        String sourceLang = "";
        String targetLang = "zh-CN";

        getTranslate(text, sourceLang, targetLang);
    }

    // 调用Google翻译
    public static JSONObject getTranslate(String text, String sourceLang, String targetLang) {

        log.debug("调用Google翻译入参信息-sourceLang:" + sourceLang + " targetLang:" + targetLang + " text:" + text);
        JSONObject resTrans = new JSONObject();

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");

        Map<String, String> params = new HashMap<>();
        params.put("q", text);
        params.put("source", sourceLang);
        params.put("target", targetLang);

        params.put("key", apiKey);

        try {

            String output = Util.doHttpPostUseHead(transURL, getMapToForm(params), "UTF-8", 5000, 0, headMap);
            log.debug("调用Google翻译返回信息-output:" + output);

            // 解析处理返回结果
            resTrans = JSONObject.fromObject(output);
            if (resTrans.has("error")) {
                // 调用异常
                resTrans.put("code", resTrans.getJSONObject("error").getInt("code"));
                resTrans.put("message", resTrans.getJSONObject("error").getString("message"));
            } else {
                // 调用成功
                resTrans.put("code", 0);
                resTrans.put("message", "调用成功");

            }
        } catch (Exception e) {
            log.error("调用Google翻译接口处理异常", e);
            resTrans.put("code", -1);
            resTrans.put("message", "调用Google翻译调用异常:" + e.getMessage());
        }

        log.debug("调用Google翻译返回信息-最终结果:" + resTrans);
        return resTrans;
    }

    /**
     * @param params: 入参信息Map
     * @return String
     * @author LiJT
     * @description TODO
     * @date 2023-09-27 15:27
     */
    public static String getMapToForm(Map<String, String> params) {
        if (params == null) {
            return "";
        }

        StringBuilder builder = new StringBuilder();

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     *
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }
}